package wzh.hc.model;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.xml.bind.annotation.adapters.HexBinaryAdapter;

public class HashComputer {

	public String compute(URI fileUri,String algorithm) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance(algorithm);
		String result;
		File file=new File(fileUri);
		if (file == null || !file.exists()) {
			result = "file doesn't exist";
		}
		result = file.getAbsolutePath();
		if (md == null) {
			result = "algorithm doesn't exist";
		} else {
			try {
				result = new HexBinaryAdapter().marshal(md
						.digest(getBytesFromFile(file)));
			} catch (Exception e) {
				result = "exception happened when reading file";
			}
		}
		return result;
	}
	
	public static byte[] getBytesFromFile(File f) throws Exception {
		if (f == null) {
			return null;
		}
		FileInputStream stream = new FileInputStream(f);
		ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
		byte[] b = new byte[1000];
		int n;
		while ((n = stream.read(b)) != -1)
			out.write(b, 0, n);
		stream.close();
		out.close();
		return out.toByteArray();
	}
}
